package com.corpgovernment.supplier.service;

import static com.corpgovernment.organization.constant.OrganizationResponseCodeEnum.REQUEST_PARAM_ERROR;
import static com.corpgovernment.organization.metric.MetricService.ORGANIZATION_SUPPLIER_COMPANY_NONE;
import static com.corpgovernment.supplier.constant.SupplierCompanyConstant.COMPANY_CODE;
import static com.corpgovernment.supplier.constant.SupplierCompanyConstant.IS_DELETED;
import static com.corpgovernment.supplier.constant.SupplierCompanyConstant.IS_ENABLE;
import static com.corpgovernment.supplier.constant.SupplierCompanyConstant.PRODUCT_TYPE;
import static com.corpgovernment.supplier.constant.SupplierCompanyConstant.SUPPLIER_CODE;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.corpgovernment.api.organization.enums.SwitchEnum;
import com.corpgovernment.api.organization.model.switchinfo.GetAllSwitchResponse;
import com.corpgovernment.api.organization.model.switchinfo.GetSwitchListRequest;
import com.corpgovernment.api.organization.model.switchinfo.SaveSwitchInfoRequest;
import com.corpgovernment.api.organization.model.switchinfo.SwitchInfoSoa;
import com.corpgovernment.api.supplier.bo.suppliercompany.GetSupplierCompanyRequestBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.GetSupplierProductRequestBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.ListPubOwnRequestBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.ListSupplierCompanyRequestBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.ListSupplierProductRequestBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.SupplierCompanyBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.SupplierCompanyContractBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.SupplierProductBo;
import com.corpgovernment.api.supplier.bo.suppliercompany.querycompanysupplierproduct.QueryCompanySupplierProductRequest;
import com.corpgovernment.api.supplier.bo.suppliercompany.querycompanysupplierproduct.QueryCompanySupplierProductResponse;
import com.corpgovernment.api.supplier.soa.constant.ProductTypeEnum;
import com.corpgovernment.api.supplier.vo.request.ListSupplierUrlReqVo;
import com.corpgovernment.api.supplier.vo.response.ListSupplierUrlRespVo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.SiteEnum;
import com.corpgovernment.common.operatelog.constant.OperateLogContant;
import com.corpgovernment.common.utils.DateUtil;
import com.corpgovernment.common.utils.Null;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.mapper.MbOrgTravelAttributeRelationMapper;
import com.corpgovernment.organization.metric.MetricService;
import com.corpgovernment.organization.operatelog.service.pojo.CompanyPojo;
import com.corpgovernment.organization.service.ISwitchService;
import com.corpgovernment.redis.cache.RedisUtils;
import com.corpgovernment.supplier.constant.CommonConstant;
import com.corpgovernment.supplier.converter.SupplierCompanyContractConverter;
import com.corpgovernment.supplier.dto.MbSupplierProductDto;
import com.corpgovernment.supplier.dto.SupplierCompanyDto;
import com.corpgovernment.supplier.dto.SupplierCompanyRequest;
import com.corpgovernment.supplier.entity.db.MbSupplierInfo;
import com.corpgovernment.supplier.entity.db.MbSupplierProduct;
import com.corpgovernment.supplier.entity.db.SupplierCompany;
import com.corpgovernment.supplier.entity.db.SupplierCompanyContract;
import com.corpgovernment.supplier.enums.ProductSupplierRuleEnum;
import com.corpgovernment.supplier.enums.PubOwnOptionEnum;
import com.corpgovernment.supplier.mapper.MbSupplierProductMapper;
import com.corpgovernment.supplier.mapper.SupplierCompanyContractMapper;
import com.corpgovernment.supplier.mapper.SupplierCompanyMapper;
import com.corpgovernment.supplier.util.CtripEncryptUtil;
import com.corpgovernment.supplier.vo.suppliercompany.AddOrUpdateRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.DeleteRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.EnableRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.InitRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.InitResponseVo;
import com.corpgovernment.supplier.vo.suppliercompany.ListRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.SortRequestVo;
import com.corpgovernment.supplier.vo.suppliercompany.SortedSupplierInfoVo;
import com.corpgovernment.supplier.vo.suppliercompany.SupplierCompanyContractVo;
import com.corpgovernment.supplier.vo.suppliercompany.SupplierCompanyVo;
import com.corpgovernment.supplier.vo.suppliercompany.SupplierInfoVo;
import com.corpgovernment.supplier.vo.suppliercompany.SupportSupplierInfoVo;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.Conditional;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

/**
 * @author jhxue
 */
@Service
@AllArgsConstructor
@Slf4j
public class SupplierCompanyService {

    private final SupplierCompanyMapper supplierCompanyMapper;
    private final SupplierCompanyContractMapper supplierCompanyContractMapper;
    private final MbSupplierInfoService supplierInfoService;
    private final ISwitchService switchService;
    private final MbSupplierProductMapper supplierProductMapper;
    private final MbSupplierInfoService msiSrv;
    @Autowired
    private MbOrgTravelAttributeRelationMapper mbOrgTravelAttributeRelationMapper;
    @Autowired
    private RedisUtils redisUtils;
    // 不需要特殊处理的操作类型
    private final List<String> operateTypeList = Lists.newArrayList("queryStationToStation", "getFlights");

    private final static String REFRESH_SUPPLIER_CACHE_KEY = "Supplier_Company_ALL";



    public Map<String, SortedSupplierInfoVo> list(ListRequestVo requestVo) {
        // 获取供应商公司关系信息
        String companyCode = requestVo.getCompanyCode();
        List<SupplierCompanyDto> supplierCompanyList = supplierCompanyMapper.selectByCompanyCode(companyCode);
        Map<String, List<SupplierCompanyDto>> supplierCompanyDtoMap = supplierCompanyList.stream().collect(Collectors.groupingBy(SupplierCompanyDto::getProductType));
		// 获取所有可用供应商信息
		List<MbSupplierInfo> supplierInfoList = supplierInfoService.loadAvailSuppliers();
		Map<String, List<MbSupplierInfo>> supplierInfoMap = toSupplierInfoMap(supplierInfoList);
		// 获取开关信息
		GetSwitchListRequest request = new GetSwitchListRequest();
		request.setOrgId(companyCode);
		GetAllSwitchResponse switchListResponse = switchService.allSwitch(request);
		Map<String, String> switchMap = switchListResponse.getSupplierCompanyValue();
		log.info("SupplierCompanyService.list switchMap：{}", JsonUtils.toJsonString(switchMap));
		Map<String, SortedSupplierInfoVo> supplierMap = Maps.newHashMap();
		// 根据产线组装数据
		log.info("SupplierCompanyService.list 支持的产线：{}", Arrays.toString(ProductTypeEnum.values()));
		Arrays.stream(ProductTypeEnum.values()).forEach(e -> {
			String productType = e.name();
			List<MbSupplierInfo> value = supplierInfoMap.get(productType);
			SortedSupplierInfoVo vo = new SortedSupplierInfoVo();
			List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyDtoMap.get(productType);
			List<String> supplierCodeList = Optional.ofNullable(value).map(v -> v.stream().map(MbSupplierInfo::getSupplierCode).collect(Collectors.toList())).orElse(Lists.newArrayList());
			Optional.ofNullable(supplierCompanyDtoList).ifPresent(s -> {
				vo.setSuppliers(s.stream().map(SupplierInfoVo::toSupplierInfoVo).collect(Collectors.toList()));
				vo.setSort(s.stream().map(SupplierCompanyDto::getSupplierCode).collect(Collectors.toList()));
				s.forEach(dto -> supplierCodeList.remove(dto.getSupplierCode()));
            });
            vo.setHasSupplier(CollectionUtils.isNotEmpty(supplierCodeList));
            vo.setProductType(productType);
            vo.setIsEnable(Optional.ofNullable(switchMap.get(companyCode + "_" + productType)).map(f -> Objects.equals(f, "1")).orElse(false));
            vo.setShowAddButton(CollectionUtils.isNotEmpty(supplierCodeList) && toShowAddButton(productType, supplierCompanyDtoList));
            vo.setAddSupplierBusPriType(toAddSupplierBusPriType(productType, supplierCompanyDtoList));
            supplierMap.put(productType, vo);
        });
        return supplierMap;
    }

    /**
     * 单供应商区分因公因私时 1因私 2 因公 3因公因私
     */
    private Integer toAddSupplierBusPriType(String productType, List<SupplierCompanyDto> supplierCompanyDtoList) {
        // 多供应商都允许新增
        if (ProductSupplierRuleEnum.PUB_OWN_SINGLE_SUPPLIER.getProductTypeList().contains(productType)) {
            if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
                return 3;
            }
            List<Integer> busPriTypeList = supplierCompanyDtoList.stream().map(SupplierCompanyDto::getBusPriType).collect(Collectors.toList());
            if (busPriTypeList.contains(3)) {
                return 0;
            }
            if (busPriTypeList.contains(1) && busPriTypeList.contains(2)) {
                return 0;
            }
            if (busPriTypeList.contains(1)) {
                return 2;
            }
            if (busPriTypeList.contains(2)) {
                return 1;
            }
        }
        return 0;
    }

    private Boolean toShowAddButton(String productType, List<SupplierCompanyDto> supplierCompanyDtoList) {
        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            return true;
        }
        // 多供应商都允许新增
        if (ProductSupplierRuleEnum.MULTI_SUPPLIER.getProductTypeList().contains(productType)) {
            return true;
        }
        // 火车票和国际机票因公因私最多只能用一个服务商，所以这个用位运算来判断因公因私是否已满
        if (ProductSupplierRuleEnum.PUB_OWN_SINGLE_SUPPLIER.getProductTypeList().contains(productType)) {
            Integer result = supplierCompanyDtoList.stream().map(SupplierCompanyDto::getBusPriType).reduce((sc1, sc2) -> sc1 | sc2).orElse(0);
            return (result & 3) != 3;
        }
        if (ProductSupplierRuleEnum.SINGLE_SUPPLIER.getProductTypeList().contains(productType)) {
            return CollectionUtils.isEmpty(supplierCompanyDtoList);
        }
        return false;
    }

    /**
     * 根据产线类型分组
     */
    private Map<String, List<MbSupplierInfo>> toSupplierInfoMap(List<MbSupplierInfo> supplierInfoList) {
        Map<String, List<MbSupplierInfo>> map = Maps.newHashMap();
        Arrays.stream(ProductTypeEnum.values()).forEach(e -> {
            String key = e.name();
            Integer id = e.getId();
            List<MbSupplierInfo> value = supplierInfoList.stream().filter(s -> (s.getSupportProduct() & id) == id).collect(Collectors.toList());
            map.put(key, value);
        });
        return map;
    }

    /**
     * 新增供应商公司关联信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(AddOrUpdateRequestVo requestVo) {
        SupplierCompanyVo supplierCompanyVo = requestVo.getSupplierCompany();
        SupplierCompany one = findSupplierCompany(supplierCompanyVo.getCompanyCode(), supplierCompanyVo.getSupplierCode(), supplierCompanyVo.getProductType());
        if (one != null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_ALREADY_EXISTS);
        }
        List<SupplierCompany> supplierCompanies = listByCompanyCodeAndProductType(supplierCompanyVo.getCompanyCode(), supplierCompanyVo.getProductType());
        Integer sortNum = supplierCompanies.stream().map(SupplierCompany::getSortNum).max(Integer::compareTo).orElse(0);
        SupplierCompany supplierCompany = SupplierCompanyVo.toSupplierCompany(supplierCompanyVo);
        supplierCompany.setSortNum(sortNum + 1);
        // 插入新增产线
        supplierCompanyMapper.insertSelective(supplierCompany);
        // 更新其他产线的配置
        updateByCompanyAndSupplier(supplierCompany);
        SupplierCompanyContractVo supplierCompanyContractVo = requestVo.getSupplierCompanyContract();
        SupplierCompanyContract supplierCompanyContract = SupplierCompanyContractVo.toSupplierCompanyContact(supplierCompanyContractVo);
        supplierCompanyContract.setSupplierCompanyId(supplierCompany.getId());
        supplierCompanyContractMapper.insertSelective(supplierCompanyContract);

        refreshSupplierCache();
    }

    private SupplierCompany findSupplierCompany(String companyCode, String supplierCode, String productType) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(COMPANY_CODE, companyCode)
                .andEqualTo(PRODUCT_TYPE, productType)
                .andEqualTo(SUPPLIER_CODE, supplierCode);
        return supplierCompanyMapper.selectOneByExample(example);
    }

    /**
     * 修改供应商公司关联信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(AddOrUpdateRequestVo requestVo) {
        SupplierCompanyVo supplierCompanyVo = requestVo.getSupplierCompany();
        SupplierCompany supplierCompany = SupplierCompanyVo.toSupplierCompany(supplierCompanyVo);
        boolean exists = supplierCompanyMapper.existsWithPrimaryKey(supplierCompany.getId());
        if (!exists) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DONT_EXISTS);
        }
        SupplierCompanyContractVo supplierCompanyContractVo = requestVo.getSupplierCompanyContract();
        SupplierCompanyContract supplierCompanyContract = SupplierCompanyContractVo.toSupplierCompanyContact(supplierCompanyContractVo);
        exists = supplierCompanyContractMapper.existsWithPrimaryKey(supplierCompanyContract.getId());
        if (!exists) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_CONTRACT_DONT_EXISTS);
        }
        updateSupplierCompany(supplierCompany);
        supplierCompanyContractMapper.updateByPrimaryKeySelective(supplierCompanyContract);

        refreshSupplierCache();
    }

    private void updateSupplierCompany(SupplierCompany supplierCompany) {
        supplierCompanyMapper.updateByPrimaryKeySelective(supplierCompany);
        // 上面只更新了该产线的供应商配置，还需要更新别的产线的主子账户配置（该配置为设计冗余，目前先保持各个产线的统一）
        updateByCompanyAndSupplier(supplierCompany);
    }

    /**
     * 同一个公司同一个供应商的情况下，不同产线的账户配置应该是相同的
     * 所以在更新一个产线的时候需要更新所有产线的
     * （更新是产线维度的更新）
     */
    private void updateByCompanyAndSupplier(SupplierCompany supplierCompany) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo("companyCode", supplierCompany.getCompanyCode())
                .andEqualTo("supplierCode", supplierCompany.getSupplierCode());
        SupplierCompany specificFieldUpdateDo = new SupplierCompany();
        specificFieldUpdateDo.setSupplierAccountId(supplierCompany.getSupplierAccountId());
        specificFieldUpdateDo.setSubAccountCode(supplierCompany.getSubAccountCode());
        specificFieldUpdateDo.setOpenCardType(supplierCompany.getOpenCardType());
        // 根据公司id和供应商code，更新子账户和主账户配置
        supplierCompanyMapper.updateByExampleSelective(specificFieldUpdateDo , example);
    }

    /**
     * 删除供应商公司关联信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(DeleteRequestVo requestVo) {
        List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyMapper.selectByCompanyCode(requestVo.getCompanyCode());
        if (supplierCompanyDtoList.stream().noneMatch(e -> Objects.equals(e.getId(), requestVo.getId()))) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DONT_EXISTS);
        }
        int result = supplierCompanyMapper.deleteById(requestVo.getId());
        if (result < 1) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DEL_ERROR);
        }

        refreshSupplierCache();
    }

    /**
     * 初始化供应商公司关联信息
     */
    public InitResponseVo init(InitRequestVo requestVo) {
        InitResponseVo responseVo = new InitResponseVo();
        String supplierCode = requestVo.getSupplierCode();
        String productType = requestVo.getProductType();
        String companyCode = requestVo.getCompanyCode();
        if (StringUtils.isNotBlank(supplierCode)) {
            // 存在供应商code -》 编辑
            SupplierCompany supplierCompany = findSupplierCompany(companyCode, supplierCode, productType);
            if (supplierCompany == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DONT_EXISTS);
            }
            MbSupplierInfo mbSupplierInfo = supplierInfoService.loadBySupplierCode(supplierCompany.getSupplierCode());
            responseVo.setSupplierCompany(SupplierCompanyVo.toSupplierCompanyVo(supplierCompany, mbSupplierInfo));
            SupplierCompanyContract supplierCompanyContract = supplierCompanyContractMapper.selectBySupplierCompanyId(supplierCompany.getId());
            responseVo.setSupplierCompanyContract(SupplierCompanyContractVo.toSupplierCompanyContactVo(supplierCompanyContract));
        } else {
            // 不存在供应商code -》新增
            ProductTypeEnum productTypeEnum = ProductTypeEnum.loadByName(productType);
            List<MbSupplierInfo> supplierInfoList = supplierInfoService.provideProductSuppliers(productTypeEnum);
            List<SupplierCompany> supplierCompanyList = listByCompanyCodeAndProductType(companyCode, productType);
            // 已关联当前产线的供应商集合
            List<String> supplierCodeList = supplierCompanyList.stream().map(SupplierCompany::getSupplierCode).collect(Collectors.toList());
            List<SupplierInfoVo> supplierInfoVoList = supplierInfoList.stream().filter(e -> !supplierCodeList.contains(e.getSupplierCode())).map(SupplierInfoVo::toSupplierInfoVo).collect(Collectors.toList());
            responseVo.setSupplierInfoList(supplierInfoVoList);
        }
        if (CommonConstant.CTRIP_CODE.equalsIgnoreCase(requestVo.getSupplierCode())){
            responseVo.setDisplayAuthorizeConfig(CommonConstant.T);
        } else {
            responseVo.setDisplayAuthorizeConfig(CommonConstant.F);
        }
        responseVo.setPubOwnOptionType(toPubOwnOptionType(requestVo));

        refreshSupplierCache();
        return responseVo;
    }


    public CompanyPojo convertCompanyPojo(InitRequestVo requestVo) {
        InitResponseVo initResponseVo = this.init(requestVo);
        CompanyPojo companyPojo = new CompanyPojo();
        if (initResponseVo != null) {
            //供应商公司关联信息
            SupplierCompanyVo supplierCompany = initResponseVo.getSupplierCompany();
            if (supplierCompany != null) {
                companyPojo = JsonUtils.convert(supplierCompany, CompanyPojo.class);
                companyPojo.setIsEnable(supplierCompany.getIsEnable() ? "启用" : "停用");
                //1表示因公，2表示因私 3表示因公因私
                if (Objects.equals(OperateLogContant.POST_UPDATE, supplierCompany.getBusPriType())) {
                    companyPojo.setBusPriType("因公");
                } else if (Objects.equals(OperateLogContant.POST_DEL, supplierCompany.getBusPriType())) {
                    companyPojo.setBusPriType("因私");
                } else {
                    companyPojo.setBusPriType("因公,因私");
                }
                //服务费获取类型 1从配置读取 2从服务商接口读取
                if (Objects.equals(NumberUtils.INTEGER_ONE, supplierCompany.getServiceFeeOptionType())) {
                    companyPojo.setServiceFeeOptionType("从服务商接口读取");
                } else {
                    companyPojo.setServiceFeeOptionType("从配置读取(元/人程)");
                }
                //1开启选择保险 2关闭选择保险 3强制购买保险
                switch (supplierCompany.getInsuranceOptionType().intValue()) {
                    case 1:
                        companyPojo.setInsuranceOptionType("开启保险");
                        break;
                    case 2:
                        companyPojo.setInsuranceOptionType("关闭保险");
                        break;
                    default:
                        companyPojo.setInsuranceOptionType("强制购买");
                        break;
                }
                companyPojo.setProductType(SiteEnum.getByCodeThenAlias(supplierCompany.getProductType()).getDesc());
                //供应商公司合同信息
                SupplierCompanyContractVo supplierCompanyContract = initResponseVo.getSupplierCompanyContract();
                if (supplierCompanyContract != null) {
                    companyPojo.setFileLoad(StringUtils.isBlank(supplierCompanyContract.getContractUrl()) ? "未上传" : "已上传");
                    String startDate = supplierCompanyContract.getStartDate();
                    startDate = startDate.indexOf(" ") != -1 ? startDate.split(" ")[0] : startDate;
                    String endDate = supplierCompanyContract.getEndDate();
                    endDate = endDate.indexOf(" ") != -1 ? endDate.split(" ")[0] : endDate;
                    companyPojo.setStartAndEndDate(startDate + "-" + endDate);
                    companyPojo.setContractNo(supplierCompanyContract.getContractNo());
                    companyPojo.setPhone(supplierCompanyContract.getPhone());
                    companyPojo.setSignPerson(supplierCompanyContract.getSignPerson());
                }
            }
        }

        return companyPojo;
    }


    public CompanyPojo convertDelPojo(DeleteRequestVo requestVo) {
        List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyMapper.selectByCompanyCode(requestVo.getCompanyCode());
        if (supplierCompanyDtoList.stream().noneMatch(e -> Objects.equals(e.getId(), requestVo.getId()))) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DONT_EXISTS);
        }
        if (CollectionUtils.isNotEmpty(supplierCompanyDtoList)) {
            SupplierCompanyDto get = null;
            for (SupplierCompanyDto supplierCompanyDto : supplierCompanyDtoList) {
                if (Objects.equals(supplierCompanyDto.getId(), requestVo.getId())) {
                    get = supplierCompanyDto;
                    break;
                }
            }
            if (get != null) {
                InitRequestVo initRequestVo = new InitRequestVo();
                initRequestVo.setSupplierCode(get.getSupplierCode());
                initRequestVo.setProductType(get.getProductType());
                initRequestVo.setCompanyCode(requestVo.getCompanyCode());
                CompanyPojo companyPojo = this.convertCompanyPojo(initRequestVo);
                return companyPojo;
            }
        }
        return null;
    }

    private Integer toPubOwnOptionType(InitRequestVo requestVo) {
        String supplierCode = requestVo.getSupplierCode();
        String companyCode = requestVo.getCompanyCode();
        String productType = requestVo.getProductType();
        List<SupplierCompany> supplierCompanyList = listByCompanyCodeAndProductType(companyCode, productType);
        if (ProductSupplierRuleEnum.MULTI_SUPPLIER.getProductTypeList().contains(productType)) {
            return multiSupplier();
        }
        if (ProductSupplierRuleEnum.PUB_OWN_SINGLE_SUPPLIER.getProductTypeList().contains(productType)) {
            return pubOwnSupplier(supplierCompanyList, supplierCode);
        }
        if (ProductSupplierRuleEnum.SINGLE_SUPPLIER.getProductTypeList().contains(productType)) {
            return singleSupplier(supplierCompanyList, supplierCode);
        }
        return PubOwnOptionEnum.OTHER.getValue();
    }

    /**
     * "因公/因私"可以支持各一个服务商
     */
    private Integer pubOwnSupplier(List<SupplierCompany> supplierCompanyList, String supplierCode) {
        if (CollectionUtils.isEmpty(supplierCompanyList)) {
            return PubOwnOptionEnum.PUB_OR_OWN.getValue();
        }
        List<SupplierCompany> supplierCompanies = supplierCompanyList.stream().filter(e -> !Objects.equals(supplierCode, e.getSupplierCode())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(supplierCompanies)) {
            // 不存在其他供应商因公因私均可选
            return PubOwnOptionEnum.PUB_OR_OWN.getValue();
        }
        // 存在其他供应商
        SupplierCompany supplierCompany = supplierCompanies.get(0);
        // 配置过因公可选因私
        if (supplierCompany.getBusPriType() == PubOwnOptionEnum.PUB.getValue()) {
            return PubOwnOptionEnum.OWN.getValue();
        }
        // 配置过因私可选因公
        if (supplierCompany.getBusPriType() == PubOwnOptionEnum.OWN.getValue()) {
            return PubOwnOptionEnum.PUB.getValue();
        }
        // 否则都不可选
        return PubOwnOptionEnum.OTHER.getValue();
    }

    /**
     * 支持单供应商
     */
    private Integer singleSupplier(List<SupplierCompany> supplierCompanyList, String supplierCode) {
        if (CollectionUtils.isEmpty(supplierCompanyList)) {
            return PubOwnOptionEnum.PUB_OR_OWN.getValue();
        }
        int size = supplierCompanyList.size();
        // 只有一个供应商并且和当前供应商一致
        if (size == 1 && Objects.equals(supplierCompanyList.get(0).getSupplierCode(), supplierCode)) {
            return PubOwnOptionEnum.PUB_OR_OWN.getValue();
        }
        return PubOwnOptionEnum.OTHER.getValue();
    }

    /**
     * 支持多供应商
     */
    private Integer multiSupplier() {
        return PubOwnOptionEnum.PUB_OR_OWN.getValue();
    }

    /**
     * 供应商信息排序
     */
    @Transactional(rollbackFor = Exception.class)
    public void sort(SortRequestVo requestVo) {
        String productType = requestVo.getProductType();
        String companyCode = requestVo.getCompanyCode();
        List<String> supplierCodeList = requestVo.getSupplierCodeList();
        List<SupplierCompany> supplierCompanies = listByCompanyCodeAndProductType(companyCode, productType);
        Map<String, SupplierCompany> supplierCompanyMap = supplierCompanies.stream().collect(Collectors.toMap(SupplierCompany::getSupplierCode, e -> e, (e1, e2) -> e1));
        if (supplierCodeList.size() != supplierCompanies.size()) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_CODE_DIFFERENCE);
        }
        for (int i = 0; i < supplierCodeList.size(); i++) {
            SupplierCompany supplierCompany = supplierCompanyMap.get(supplierCodeList.get(i));
            supplierCompany.setSortNum(i + 1);
        }
        supplierCompanies.forEach(supplierCompanyMapper::updateSortNumById);
    }

    private List<SupplierCompany> listByCompanyCodeAndProductType(String companyCode, String productType) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(COMPANY_CODE, companyCode)
                .andEqualTo(PRODUCT_TYPE, productType);
        return supplierCompanyMapper.selectByExample(example);
    }

    /**
     * 启用停用产线
     */
    public void enable(EnableRequestVo requestVo) {
        String companyCode = requestVo.getCompanyCode();
        String productType = requestVo.getProductType();
        Boolean isEnable = requestVo.getIsEnable();
        String value = isEnable ? "1" : "0";
        //查询开关
        SwitchEnum switchEnum = null;
        if ("flight".equals(productType)) {
            switchEnum = SwitchEnum.FLIGHT_SUPPLIER_CONTROL;
        } else if ("train".equals(productType)) {
            switchEnum = SwitchEnum.TRAIN_SUPPLIER_CONTROL;
        } else if ("car".equals(productType)) {
            switchEnum = SwitchEnum.CAR_SUPPLIER_CONTROL;
        } else if ("hotel".equals(productType)) {
            switchEnum = SwitchEnum.HOTEL_SUPPLIER_CONTROL;
        } else if ("intlflight".equals(productType)) {
            switchEnum = SwitchEnum.INTLFLIGHT_SUPPLIER_CONTROL;
        } else if ("hotelintl".equals(productType)) {
            switchEnum = SwitchEnum.HOTELINTL_SUPPLIER_CONTROL;
        } else if ("airportTransfer".equals(productType)) {
			switchEnum = SwitchEnum.AIRPORTTRANSFER_SUPPLIER_CONTROL;
		}else if ("trainTransfer".equals(productType)) {
			switchEnum = SwitchEnum.TRAINTRANSFER_SUPPLIER_CONTROL;
		}
		if (switchEnum == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PRODUCT_TYPE_ERROR);
        }
        GetSwitchListRequest getSwitchListRequest = new GetSwitchListRequest();
        getSwitchListRequest.setOrgId(companyCode);
        GetAllSwitchResponse response = switchService.allSwitch(getSwitchListRequest);
        Map<String, SwitchInfoSoa> supplierCompanyMap = response.getSupplierCompany();
        SwitchInfoSoa switchInfoVo = supplierCompanyMap.get(switchEnum.getKey());
        SaveSwitchInfoRequest saveSwitchInfoRequest = new SaveSwitchInfoRequest();
        saveSwitchInfoRequest.setOrgId(companyCode);
        SwitchInfoSoa newSwitchInfo = new SwitchInfoSoa();
        if (switchInfoVo == null) {
            newSwitchInfo.setOrgId(companyCode);
            newSwitchInfo.setValue(value);
            newSwitchInfo.setSwitchName(switchEnum.getName());
            newSwitchInfo.setSwitchKey(switchEnum.getKey());
        } else {
            newSwitchInfo.setSwitchId(switchInfoVo.getSwitchId());
            newSwitchInfo.setValue(value);
        }
        try {
            switchService.saveOrgSwitchSoa(newSwitchInfo);
        } catch (Exception e) {
            log.error("更新开关失败:", e);
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SWITCH_OPEN_ERROR);
        }

    }

    /**
     * 查询企业订购的供应商信息
     */
    public SupplierProductBo findSupplierProduct(GetSupplierProductRequestBo requestBo) {
        String supplierCode = requestBo.getSupplierCode();
        String operateType = requestBo.getOperateType();
        String productType = requestBo.getProductType();
        List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyMapper.selectByRequest(SupplierCompanyRequest.toRequest(requestBo));
        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            log.info("企业没有订购该服务");
            return null;
        }
        // list操作需要过滤出可用的 合同未过期的企业订购业务
        Date date = Optional.ofNullable(DateUtil.stringToDate(DateUtil.dateToString(new Date(), DateUtil.DF_YMD), DateUtil.DF_YMD)).orElse(new Date());
        if (!operateTypeList.contains(operateType)) {
            supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(e -> e.getEndDate().compareTo(date) >= 0 && e.getStartDate().compareTo(date) <= 0 && e.getIsEnable()).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            log.info("企业订购的该服务已过期或者已停用");
            MetricService.metricSupplierCounter(ORGANIZATION_SUPPLIER_COMPANY_NONE);
            return null;
        }
        MbSupplierProductDto supplierProductDto = supplierProductMapper.selectBySupplierCodeAndProductTypeAndOperateType(supplierCode, productType, operateType);
        if (supplierProductDto == null) {
            MetricService.metricSupplierCounter(ORGANIZATION_SUPPLIER_COMPANY_NONE);
            log.info("企业订购的该服务没有配置对应得产");
            return null;
        }

        Optional<SupplierCompanyDto> firstSupplierCompany = supplierCompanyDtoList.stream().filter(item -> StringUtils.isNotBlank(item.getSupplierCorpId())).findFirst();
        SupplierCompanyDto supplierCompanyDto = null;
        if (firstSupplierCompany.isPresent()) {
            supplierCompanyDto = firstSupplierCompany.get();
        } else {
            supplierCompanyDto = supplierCompanyDtoList.get(0);
        }
        SupplierProductBo responseBo = new SupplierProductBo();
        BeanUtils.copyProperties(supplierProductDto, responseBo);
        responseBo.setSupplierUid(supplierCompanyDto.getSupplierUid());
        responseBo.setSupplierCorpId(supplierCompanyDto.getSupplierCorpId());
        responseBo.setProductUrl(CtripEncryptUtil.encrypt(supplierProductDto.getProductUrl()));
        return responseBo;
    }

    public List<MbSupplierInfo> loadSupplierInfo4Company(List<String> supplierCodes, String companyCode) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andIn(SUPPLIER_CODE, supplierCodes)
                .andEqualTo(COMPANY_CODE, companyCode)
                .andEqualTo(IS_DELETED, false)
                .andEqualTo("isEnable", true);
        List<SupplierCompany> supplierCompanies = supplierCompanyMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(supplierCompanies)) {
            return Collections.emptyList();
        }
        return msiSrv.loadBySupplierCodes(supplierCompanies.stream().map(SupplierCompany::getSupplierCode).collect(Collectors.toList()));
    }

    public SupplierCompanyBo findSupplierCompany(GetSupplierCompanyRequestBo requestBo) {
        Integer busPriType = requestBo.getBusPriType();
        String companyCode = requestBo.getCompanyCode();
        String supplierCode = requestBo.getSupplierCode();
        String productType = requestBo.getProductType();
        Boolean isEnable = requestBo.getIsEnable();
        Example example = new Example(SupplierCompany.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(COMPANY_CODE, companyCode)
                .andEqualTo(SUPPLIER_CODE, supplierCode)
                .andCondition("bus_pri_type &" + busPriType);
        if (StringUtils.isNotBlank(productType)){
			criteria.andEqualTo(PRODUCT_TYPE, productType);
		}
        if (isEnable != null) {
            criteria.andEqualTo("isEnable", isEnable);
        }
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(supplierCompanyList)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SUPPLIER_COMPANY_DONT_EXISTS);
        }
        SupplierCompanyBo supplierCompanyBo = new SupplierCompanyBo();
        BeanUtils.copyProperties(supplierCompanyList.get(0), supplierCompanyBo);
        log.info("返回服务商信息:{}", JsonUtils.toJsonString(supplierCompanyBo));
        return supplierCompanyBo;
    }

    public List<SupplierCompanyBo> listSupplierCompany(ListSupplierCompanyRequestBo requestBo) {
        Integer busPriType = requestBo.getBusPriType();
        String companyCode = requestBo.getCompanyCode();
        String productType = requestBo.getProductType();
        Boolean isEnable = requestBo.getIsEnable();
        Example example = new Example(SupplierCompany.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andCondition("bus_pri_type &" + busPriType);
        if (CollectionUtils.isNotEmpty(requestBo.getCompanyCodeList())) {
            criteria.andIn(COMPANY_CODE, requestBo.getCompanyCodeList());
        } else {
            criteria.andEqualTo(COMPANY_CODE, companyCode);
        }
        if (StringUtils.isNotBlank(productType)) {
            criteria.andEqualTo(PRODUCT_TYPE, productType);
        }
        if (StringUtils.isNotBlank(requestBo.getSupplierCode())) {
            criteria.andEqualTo("supplierCode", requestBo.getSupplierCode());
        }
        if (isEnable != null) {
            criteria.andEqualTo("isEnable", isEnable);
        }
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(supplierCompanyList)) {
            return null;
        }
        List<String> supplierCodeList = supplierCompanyList.stream().map(SupplierCompany::getSupplierCode).collect(Collectors.toList());
        Map<String, MbSupplierInfo> supplierInfoMap = supplierInfoService.getSupplierInfoMap(supplierCodeList);
        List<Long> supplierCompanyIdList = supplierCompanyList.stream()
                .map(SupplierCompany::getId)
                .collect(Collectors.toList());
        List<SupplierCompanyContractBo> contractList = getCompanyContract(supplierCompanyIdList);
        Map<Long, SupplierCompanyContractBo> contractMap =
                Conditional.ofEmptyAble(contractList).orElse(Collections.emptyList())
                        .stream()
                        .collect(Collectors.toMap(SupplierCompanyContractBo::getSupplierCompanyId, Function.identity()));
        return supplierCompanyList.stream().map(t -> {
            SupplierCompanyBo supplierCompanyBo = new SupplierCompanyBo();
            BeanUtils.copyProperties(t, supplierCompanyBo);
            supplierCompanyBo.setSupplierCompanyContract(contractMap.get(t.getId()));
            supplierCompanyBo.setSupplierName(Null.or(supplierInfoMap.get(t.getSupplierCode()), MbSupplierInfo::getSupplierName,null));
            supplierCompanyBo.setSupplierFullName(Null.or(supplierInfoMap.get(t.getSupplierCode()), MbSupplierInfo::getSupplierFullName,null));
            return supplierCompanyBo;
        }).collect(Collectors.toList());

    }

    private List<SupplierCompanyContractBo> getCompanyContract(List<Long> idList){
        if (CollectionUtils.isEmpty(idList)){
            return Collections.emptyList();
        }
        List<SupplierCompanyContract> supplierCompanyList = supplierCompanyContractMapper.selectBySupplierCompanyIdList(idList);
        if (CollectionUtils.isEmpty(supplierCompanyList)){
            return Collections.emptyList();
        }
        return supplierCompanyList.stream()
                .map(SupplierCompanyContractConverter.INSTANCE::convert)
                .collect(Collectors.toList());

    }

    public List<SupplierProductBo> listSupplierProduct(ListSupplierProductRequestBo requestBo) {
        String supplierCode = requestBo.getSupplierCode();
        String operateType = requestBo.getOperateType();
        String productType = requestBo.getProductType();
        Map<String, SupplierCompanyDto> supplierCompanyMap = new HashMap<>();
        SupplierCompanyRequest supplierCompanyRequest = SupplierCompanyRequest.toRequest(requestBo);
        if (Objects.equals(productType, ProductTypeEnum.other.name())) {
            supplierCompanyRequest.setProductType(null);
        }
        List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyMapper.selectByRequest(supplierCompanyRequest);
        if (StringUtils.isNotBlank(supplierCode)) {
            supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(e -> Objects.equals(supplierCode, e.getSupplierCode())).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            log.info("企业没有订购该服务");
            return null;
        }
        // list操作需要过滤出可用的 合同未过期的企业订购业务
        supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(this::filterSupplier).collect(Collectors.toList());
        // 过滤到因私或者因公未开启的
        Integer busPriType = requestBo.getBusPriType();
        if(busPriType != null) {
            supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(
                    e-> (busPriType == 3)||Objects.equals(busPriType, e.getBusPriType()) || Objects.equals(3, e.getBusPriType())).collect(Collectors.toList());
        }
		if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
			log.info("企业订购的该服务已过期或者已停用");
			return null;
		}
		log.info("企业订购服务列表为{}", JsonUtils.toJsonString(supplierCompanyDtoList));
		supplierCompanyMap.putAll(supplierCompanyDtoList.stream().collect(Collectors.toMap(SupplierCompanyDto::getSupplierCode, e -> e, (e1, e2) -> e1)));
		List<String> supplierCodeList = Lists.newArrayList(supplierCompanyMap.keySet());
		List<MbSupplierProductDto> supplierProductList = supplierProductMapper.selectByProductTypeAndOperateTypeInSupplierCode(productType, operateType, supplierCodeList);
		return supplierProductList.stream().map(e -> {
			SupplierProductBo responseBo = new SupplierProductBo();
			BeanUtils.copyProperties(e, responseBo);
			SupplierCompanyDto supplierCompanyDto = supplierCompanyMap.get(e.getSupplierCode());
			if (supplierCompanyDto != null) {
				responseBo.setSupplierUid(supplierCompanyDto.getSupplierUid());
				responseBo.setSupplierCorpId(supplierCompanyDto.getSupplierCorpId());
                responseBo.setSupplierAccountId(supplierCompanyDto.getSupplierAccountId());
			}
			responseBo.setProductUrl(CtripEncryptUtil.encrypt(e.getProductUrl()));
			return responseBo;
		}).collect(Collectors.toList());
    }

    private boolean filterSupplier(SupplierCompanyDto supplierCompany) {
        if (supplierCompany.getStartDate() == null || supplierCompany.getEndDate() == null || supplierCompany.getIsEnable() == null) {
            return false;
        }
        return supplierCompany.getEndDate().compareTo(new Date()) > 0 && supplierCompany.getStartDate().compareTo(new Date()) < 0 && supplierCompany.getIsEnable();
    }

    public List<SupportSupplierInfoVo> listSupplierInfo(String companyCode) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(COMPANY_CODE, companyCode);
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(supplierCompanyList)) {
            return null;
        }
        Map<String, String> supplierCodeMap = supplierCompanyList.stream().collect(Collectors.groupingBy(SupplierCompany::getSupplierCode, Collectors.mapping(e -> ProductTypeEnum.getByName(e.getProductType()), Collectors.joining("、"))));
        List<MbSupplierInfo> supplierInfoList = supplierInfoService.listInSupplierCode(Lists.newArrayList(supplierCodeMap.keySet()));
        Map<String, MbSupplierInfo> supplierInfoMap = supplierInfoList.stream().collect(Collectors.toMap(MbSupplierInfo::getSupplierCode, e -> e, (e1, e2) -> e1));
        List<SupportSupplierInfoVo> list = Lists.newArrayList();
        supplierCodeMap.forEach((k, v) -> {
            MbSupplierInfo supplierInfo = supplierInfoMap.get(k);
            if (supplierInfo != null) {
                SupportSupplierInfoVo vo = new SupportSupplierInfoVo();
                vo.setProduct(v);
                vo.setName(supplierInfo.getSupplierName());
                vo.setHotLine(supplierInfo.getSupplierPhone());
                list.add(vo);
            }
        });
        return list;
    }

    public List<String> listPubOwnType(ListPubOwnRequestBo requestBo) {
        String companyCode = requestBo.getCompanyCode();
        String supplierCode = requestBo.getSupplierCode();
        String productType = requestBo.getProductType();
        Example example = new Example(SupplierCompany.class);
        Example.Criteria criteria = example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(IS_ENABLE, true)
                .andEqualTo(PRODUCT_TYPE, productType)
                .andEqualTo(COMPANY_CODE, companyCode);
        if (StringUtils.isNotBlank(supplierCode)) {
            criteria.andEqualTo(SUPPLIER_CODE, supplierCode);
        }
        List<SupplierCompany> supplierCompany = supplierCompanyMapper.selectByExample(example);
        List<Integer> burPriTypeList = supplierCompany.stream().map(SupplierCompany::getBusPriType).collect(Collectors.toList());
        return toPubOwnTypeList(burPriTypeList);
    }

    /**
     * busPriType转换为pub own
     */
    private List<String> toPubOwnTypeList(List<Integer> busPriTypeList) {
        if (CollectionUtils.isEmpty(busPriTypeList)) {
            return null;
        }
        if (busPriTypeList.contains(3) || (busPriTypeList.contains(2) && busPriTypeList.contains(1))) {
            return Lists.newArrayList("OWN", "PUB");
        }
        if (busPriTypeList.contains(1)) {
            return Lists.newArrayList("PUB");
        } else if (busPriTypeList.contains(2)) {
            return Lists.newArrayList("OWN");
        }
        return null;
    }

    public List<String> listBySupplierCode(String supplierCode) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andEqualTo(IS_ENABLE, true)
                .andEqualTo(SUPPLIER_CODE, supplierCode);
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        return CollectionUtils.isEmpty(supplierCompanyList) ? null : supplierCompanyList.stream().map(SupplierCompany::getCompanyCode).distinct().collect(Collectors.toList());
    }

    public List<SupplierCompanyBo> listByOrgIds(List<String> orgIds) {
        Example example = new Example(SupplierCompany.class);
        example.createCriteria()
                .andEqualTo(IS_DELETED, false)
                .andIn(COMPANY_CODE, orgIds);
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        return supplierCompanyList.stream().map(e -> {
            SupplierCompanyBo supplierCompanyBo = new SupplierCompanyBo();
            BeanUtils.copyProperties(e, supplierCompanyBo);
            return supplierCompanyBo;
        }).collect(Collectors.toList());
    }

    public QueryCompanySupplierProductResponse queryCompanySupplierProduct(
        QueryCompanySupplierProductRequest request) {

        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.queryCompanySupplierProduct(
            request.getOrgIds(), request.getSupplierCode());

        List<String> productList = supplierCompanyList.stream()
            .map(SupplierCompany::getProductType)
            .filter(StringUtils::isNotBlank)
            .distinct().collect(Collectors.toList());

        QueryCompanySupplierProductResponse response = new QueryCompanySupplierProductResponse();
        response.setAllProductTypeList(productList);
        return response;
    }

    public SupplierProductBo findCorpIdBySupplierCode(GetSupplierCompanyRequestBo requestBo) {
        String supplierCode = requestBo.getSupplierCode();
        SupplierCompanyRequest supplierCompanyRequest = SupplierCompanyRequest.toRequest(requestBo);
        List<SupplierCompanyDto> supplierCompanyDtoList = supplierCompanyMapper.selectByRequest(supplierCompanyRequest);
        if (StringUtils.isNotBlank(supplierCode)) {
            supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(e -> Objects.equals(supplierCode, e.getSupplierCode())).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            log.info("企业没有订购该服务");
            return null;
        }
        // list操作需要过滤出可用的 合同未过期的企业订购业务
        supplierCompanyDtoList = supplierCompanyDtoList.stream().filter(this::filterSupplier).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(supplierCompanyDtoList)) {
            log.info("企业订购的该服务已过期或者已停用");
            return null;
        }
        SupplierProductBo bo = new SupplierProductBo();
        bo.setSupplierCorpId(supplierCompanyDtoList.get(0).getSupplierCorpId());
        return bo;
    }


    private void refreshSupplierCache(){
        Example example = new Example(SupplierCompany.class);
        example.createCriteria().andEqualTo(IS_DELETED, false);
        List<SupplierCompany> supplierCompanyList = supplierCompanyMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(supplierCompanyList)){
            if (StringUtils.isNotBlank(redisUtils.getCache(REFRESH_SUPPLIER_CACHE_KEY))){
                redisUtils.delete(REFRESH_SUPPLIER_CACHE_KEY);
            }
            redisUtils.setCache(REFRESH_SUPPLIER_CACHE_KEY, JsonUtils.toJsonString(supplierCompanyList), 60 * 10);
        }
    }


    public List<SupplierCompanyDto> getSupplierCompanySoa(){
        String cache = redisUtils.getCache(REFRESH_SUPPLIER_CACHE_KEY);
        if (StringUtils.isBlank(cache)){
            refreshSupplierCache();
            cache = redisUtils.getCache(REFRESH_SUPPLIER_CACHE_KEY);
        }

        List<SupplierCompany> supplierCompanies = JsonUtils.parseArray(cache, SupplierCompany.class);
        if (CollectionUtils.isEmpty(supplierCompanies)){
            // todo 缓存拿不到直接返回空不合理，应该再查一遍数据库
            return Collections.emptyList();
        }

        List<SupplierCompanyDto> resultList = Lists.newArrayList();
        supplierCompanies.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(p -> p.getSupplierCode() + "_" + p.getSupplierCorpId() + "_" + p.getSupplierUid()))
                        ), ArrayList::new)).stream().filter(item -> Objects.nonNull(item)).forEach(item ->{
            SupplierCompanyDto supplierCompanyDto = new SupplierCompanyDto();
            supplierCompanyDto.setSupplierUid(item.getSupplierUid());
            supplierCompanyDto.setSupplierCorpId(item.getSupplierCorpId());
            supplierCompanyDto.setSupplierCode(item.getSupplierCode());
            resultList.add(supplierCompanyDto);
        });
        return resultList;
    }

    /**
     * 根据supplierCode查询配置当前供应商的公司信息
     * @param supplierCode
     * @return
     */
    public List<SupplierCompanyDto> querySupplierCompanyBySupplierCode(String supplierCode) {

        return supplierCompanyMapper.querySupplierCompanyBySupplierCode(supplierCode).stream().map(item -> {
            SupplierCompanyDto dto = new SupplierCompanyDto();
            dto.setCompanyCode(item.getCompanyCode());
            return dto;
        }).collect(Collectors.toList());
    }

    public ListSupplierUrlRespVo listSupplierUrl(ListSupplierUrlReqVo requestParam) {
        List<ListSupplierUrlReqVo.SupplierKey> supplierKeyList = requestParam.getSupplierKeyList();
        String productType = requestParam.getProductType();
        if (StringUtils.isBlank(productType) || CollectionUtils.isEmpty(supplierKeyList)) {
            throw new CorpBusinessException(REQUEST_PARAM_ERROR);
        }
        ListSupplierUrlRespVo result = new ListSupplierUrlRespVo();
        List<ListSupplierUrlRespVo.SupplierUrl> supplierUrlList = new ArrayList<>(0);
        result.setSupplierUrlList(supplierUrlList);
        // 获取产线所有供应商产品
        List<MbSupplierProduct> supplierProductList = supplierProductMapper.list(requestParam.getProductType());
        log.info("supplierProductList={}", supplierProductList);
        if (CollectionUtils.isEmpty(supplierProductList)) {
            return result;
        }
        Map<String, MbSupplierProduct> tmpMap = convert(supplierProductList);
        supplierKeyList.forEach(item -> {
            String key = item.getSupplierCode() + item.getOperatorType();
            MbSupplierProduct tmp = tmpMap.get(key);
            if (tmp == null) {
                return;
            }
            supplierUrlList.add(convert(tmp));
        });
        result.setSupplierUrlList(supplierUrlList);
        return result;
    }

    private ListSupplierUrlRespVo.SupplierUrl convert( MbSupplierProduct supplierProduct) {
        ListSupplierUrlRespVo.SupplierUrl supplierUrl = new ListSupplierUrlRespVo.SupplierUrl();
        supplierUrl.setSupplierCode(supplierProduct.getSupplierCode());
        supplierUrl.setOperatorType(supplierProduct.getOperatorType());
        supplierUrl.setProductUrl(CtripEncryptUtil.encrypt(supplierProduct.getProductUrl()));
        supplierUrl.setUserKey(supplierProduct.getUserKey());
        return supplierUrl;
    }

    private Map<String, MbSupplierProduct> convert(List<MbSupplierProduct> supplierProductList) {
        Map<String, MbSupplierProduct> map = new HashMap<>();
        supplierProductList.forEach(item -> map.put(item.getSupplierCode()+item.getOperatorType(), item));
        return map;
    }

}
